package com.mjk.common.core.jdbc.util.provider;

import com.mjk.common.base.model.BaseEntity;
import com.mjk.common.core.jdbc.annotation.Id;
import com.mjk.common.core.jdbc.annotation.Transient;
import com.mjk.common.core.jdbc.service.plus.wrap.BeeQueryWrapper;
import com.mjk.common.util.ObjectUtils;
import com.mjk.common.util.ReflectionUtils;
import com.mjk.common.util.StrUtils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class UpdateSqlProvider extends SqlProvider {
    /**
     * 获取update字段
     */
    public static String getUpdateFiled(BaseEntity t) {
        List<String> sql = new ArrayList<>();
        List<Field> fields = getValidTableFiled(t, true);
        for (Field f : fields) {
            if (f.getAnnotation(Id.class) == null) {
                Object o = ReflectionUtils.getFieldValue(t, f.getName());
                if (ObjectUtils.isNotEmpty(o)) {
                    sql.add(getCloumName(f) + getFiledType("=#{dto.", t, f));
                } else if (o != null) {//如果不是null设置为空
                    sql.add(getCloumName(f) + "=''");
                }
            }
        }
        return StrUtils.join(sql, ",");
    }

    public static String getUpdateFiled(BeeQueryWrapper wrapper) {
        List<String> sql = new ArrayList<>();
        List<Field> fields = getValidTableFiled(wrapper.getInstance(), true);
        for (Field f : fields) {
            if (f.getAnnotation(Id.class) == null) {
                Object o = ReflectionUtils.getFieldValue(wrapper.getInstance(), f.getName());
                if (ObjectUtils.isNotEmpty(o)) {
                    if (wrapper.getIncList().contains(f.getName())) {//自增字段
                        sql.add(getCloumName(f) + "= " + getCloumName(f) + "+#{wrap.entity." + f.getName() + "}");
                    } else {
                        sql.add(getCloumName(f) + "=" + getFiledType("#{wrap.entity.", wrapper.getInstance(), f));
                    }
                } else if (o != null) {//如果不是null设置为空
                    sql.add(getCloumName(f) + "=''");
                }
            }
        }
        return StrUtils.join(sql, ",");
    }
}
